package com.luli.service.impl;

/**
 * 陆离
 * 2022/10/18 16:09:12
 */

import com.alibaba.druid.pool.ha.selector.StickyRandomDataSourceSelector;
import com.alibaba.fastjson.JSON;
import com.luli.Utils.JwtUtils;
import com.luli.Utils.RedisUtils;
import com.luli.dao.UsersDao;
import com.luli.entity.Menu;
import com.luli.entity.login.LoginParam;
import com.luli.entity.login.SysUsers;
import com.luli.entity.response.ResponseMsg;
import com.luli.enumeration.MessageEnum;
import com.luli.service.LoginService;
import com.luli.service.MenuService;
import com.luli.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.luli.Utils.ResponseMsgUtil.getFailMsg;
import static com.luli.Utils.ResponseMsgUtil.getSuccessMsg;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    private static final String slat = "mszlu!@#";

    @Autowired
    private UsersService usersService;

    @Autowired
    private RedisUsersServiceImpl redisUsersService;

    @Autowired
    private RedisUtils redisUtil;

    @Autowired
    private UsersDao usersDao;



    @Autowired
    private MenuService menuService;

    @Override
    public ResponseMsg<?> login(LoginParam loginParam) {
        /**
         * 1.检查用户参数是否合法
         * 2.根据用户名和密码去user表中查询 是否存在
         * 3.如果不存在，登录失败
         * 4.如果不存在，使用jwt生成token返回给前端
         * 5.token放入redis中，redis token：user信息，设置过期时间
         * （登录认证的时候，先认证token字符是否合法，去redis认证是否存在）
         */
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            return getFailMsg(MessageEnum.PARAMS_ERROR.getCode(), MessageEnum.PARAMS_ERROR.getMsg(), null);
        }
        //加密加盐
        password = DigestUtils.md5Hex(password + slat);
        SysUsers user = usersService.findUser(account, password);
        if (user == null) {
            return getFailMsg(MessageEnum.ACCOUNT_PWD_NOT_EXISTS.getCode(), MessageEnum.ACCOUNT_PWD_NOT_EXISTS.getMsg(), null);
        }
        String jwtToken = JwtUtils.createJwtToken(user.getId());
        boolean redisToken = redisUtil.set("TOKEN_" + jwtToken, JSON.toJSONString(user), 1, TimeUnit.DAYS);

        List<Menu> menusList = menuService.queryUserRole(loginParam.getRoleId());
        Map<String, Object> res = new HashMap<>();
        res.put("user",user);
        res.put("menusList",menusList);
        return getSuccessMsg(null, jwtToken, res);
    }

    @Override
    public SysUsers findUser(String account, String password) {
        SysUsers user = usersDao.findUser(account, password);
        return user;
    }


    @Override
    public ResponseMsg<?> findUserByToken(String token) {
        /**
         * 1.token合法性校验
         *  是否为空，解析是否成功，redis是否存在
         * 2.校验失败，返回错误
         * 3.如果成功，返回对应结果集 LoginUserVo
         */
        if (StringUtils.isBlank(token)) {
            return getFailMsg(MessageEnum.TOKEN_ISNULL.getCode(), MessageEnum.TOKEN_ISNULL.getMsg(), null);
        }
        Map<String, Object> stringObjectMap = JwtUtils.checkToken(token);
        if (stringObjectMap == null) {
            return getFailMsg(MessageEnum.CHECK_TOKEN_ERROR.getCode(), MessageEnum.CHECK_TOKEN_ERROR.getMsg(), null);
        }
        String userJson = String.valueOf(redisUtil.get("TOKEN_" + token));
        if (StringUtils.isBlank(userJson)){
            return getFailMsg(MessageEnum.REDIS_HAVE_EXPIRED.getCode(), MessageEnum.REDIS_HAVE_EXPIRED.getMsg(), null);
        }
        SysUsers sysUsers = JSON.parseObject(userJson, SysUsers.class);
        return getSuccessMsg("200","查询成功",sysUsers);
    }


    @Override
    public ResponseMsg<?>  delUser(String account) {
        SysUsers user = usersDao.findUser(account, null);
        if (user != null){
            //存在先删除redis

            //删除数据库
        }
        return getFailMsg(null, "用户不存在", null);
    }


    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("name","lzp");
        map.put("age","18");
        map.put("sex","男");
        //强制map不能被修改
        Map<String, Object> stringObjectMap = Collections.unmodifiableMap(map);
        stringObjectMap.put("test","9963");
        System.out.println(stringObjectMap);
    }

}
